﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Linq;

namespace Stp.Core
{
    public class CoreRegistry : IRegistry
    {
        private static CoreRegistry _registry;
        private string _currentPath;
        private List<string> _nameList;
        private XElement _plugins;

        public string CurrentPath
        {
            get { return _currentPath; }
        }

        public List<string> CountryNameList
        {
            get
            {
                return _nameList;
            }
        }

        public bool FindCountry(string countryName)
        {
            return _nameList.Exists(new Predicate<string>(item => string.Equals(item, countryName.ToUpper())));
        }

        public DatalayerInfo GetDatalayerInfo()
        {
            DatalayerInfo dInfo = new DatalayerInfo();

            XElement datalayerElement = _plugins.Element("Datalayer");
            dInfo.AssemblyName = datalayerElement.Element("Assembly").Value;
            dInfo.DefaultNamespace = datalayerElement.Element("Namespace").Value;

            return dInfo;
        }

        public static CoreRegistry GetInstance()
        {
            if (_registry == null)
            {
                _registry = new CoreRegistry();
                _registry.Initialize();
            }

            return _registry;
        }

        private void Initialize()
        {
            GetPathInfo();
            GetCountryNames();
            GetPlugins();
        }

        private void GetPathInfo()
        {
            Assembly instAssembly = Assembly.GetExecutingAssembly();
            _currentPath = Path.GetDirectoryName(instAssembly.Location);
        }

        private void GetCountryNames()
        {
            string serCountryNamesFilePath = _currentPath + "\\CtryNames.txt";

            using (FileStream fs = new FileStream(serCountryNamesFilePath, FileMode.Open, FileAccess.Read))
            {
                BinaryFormatter bf = new BinaryFormatter();
                _nameList = bf.Deserialize(fs) as List<string>;
            }
        }

        private void GetPlugins()
        {
            string pluginsFilePath = _currentPath + "\\Plugins.xml";
            _plugins = XElement.Load(pluginsFilePath);
        }
    }
}
